package com.supreme.studyserver.thread;

import com.supreme.studyserver.lambda.LoopProcessor;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 实现Runnable方法
 */
public class ImplThread implements Runnable {

    private int count = 10;
    private String threadName;
    private LoopProcessor loopProcessor;

    private static final Lock locker = new ReentrantLock(true);

    public ImplThread(int count) {
        this.count = count;
        this.threadName = Thread.currentThread().getName();
    }

    public ImplThread(int count, String threadName) {
        this.count = count;
        this.threadName = threadName;
    }

    public ImplThread(LoopProcessor loopProcessor, int count) {
        this.loopProcessor = loopProcessor;
    }

    @Override
    public void run() {
        if (this.loopProcessor != null) {
            this.loopProcessor.simpleLooper(this.count);
        } else {
            for (int i = 0; i < count; i++) {
                try {
                    locker.lock();
                    System.out.printf("QumThread %s %d\n", this.threadName, i);
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    locker.unlock();
                }
            }
        }
    }
}
